#pragma once
#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>

#include"log.hpp"

enum
{
    SOCK_ERR,
    BIND_ERR,
    LISTEN_ERR
};

const int backlog=10;
extern Log lg;

class Sock
{
public:
    Sock()
    {}
    ~Sock()
    {}

public:
    void Socket()
    {
        // 坑，不要intsock
        sockfd_=socket(AF_INET,SOCK_STREAM,0);
        if(sockfd_<0)
        {
            lg(Fatal,"socket error,errno:%d,strerr:%s",errno,strerror(errno));
            exit(SOCK_ERR);
        }
        int op=1;
        setsockopt(sockfd_,SOL_SOCKET,SO_REUSEADDR|SO_REUSEPORT,&op,sizeof(op));
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(port);
        local.sin_addr.s_addr=INADDR_ANY;

        if(bind(sockfd_,(struct sockaddr*)&local,sizeof(local))<0)
        {
            lg(Fatal,"bind error,errno:%d,strerr:%s",errno,strerror(errno));
            exit(BIND_ERR);
        }      
    }

    void Listen()
    {
        if(listen(sockfd_,backlog)<0)
        {
            lg(Fatal,"listen error,errno:%d,strerr:%s",errno,strerror(errno));
            exit(LISTEN_ERR);
        }
    }

    int Accept(std::string*clientip,uint16_t*clientport)
    {
        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        int n=accept(sockfd_,(struct sockaddr*)&peer,&len);
        if(n<0)
        {
            lg(Warning,"accept error,errno:%d,strerr:%s",errno,strerror(errno));
            return -1;
        }
        char ipbuf[128];
        inet_ntop(AF_INET,&peer.sin_addr,ipbuf,len);
        *clientip=ipbuf;
        *clientport=ntohs(peer.sin_port);
        return n;
    }

    bool Connect(const std::string& ip,const uint16_t &port)
    {
        struct sockaddr_in peer;
        peer.sin_family=AF_INET;
        peer.sin_port=htons(port);
        inet_pton(AF_INET,ip.c_str(),&peer.sin_addr);
        int n=connect(sockfd_,(struct sockaddr*)&peer,sizeof(peer));
        if(n<0)
        {
            lg(Warning,"connect err,errno:%d,strerr:%s",errno,strerror(errno));
            return false;
        }
        return true;
    }

    void Close()
    {
        close(sockfd_);
    }

    int Fd()
    {
        return sockfd_;
    }
private:
    int sockfd_;
};